/**
 * Project Name:dsrs-systemservice-web
 * File Name:GroupController.java
 * Package Name:com.bwda.dsrs.systemservice.controller;
 * Date:2019年4月28日
 * Copyright (c) 2019, 江苏保旺达软件有限公司 All Rights Reserved.
 */
package com.bwda.dsrs.systemservice.controller;


import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.CopyUtil;
import com.bwda.dsrs.systemservice.annotations.NeedRole;
import com.bwda.dsrs.systemservice.aspect.LogTypeEnum;
import com.bwda.dsrs.systemservice.aspect.Loggable;
import com.bwda.dsrs.systemservice.domain.Constants;
import com.bwda.dsrs.systemservice.domain.condition.group.GroupCondition;
import com.bwda.dsrs.systemservice.domain.condition.user.UserCondition;
import com.bwda.dsrs.systemservice.domain.condition.usergroup.UserGroupCondition;
import com.bwda.dsrs.systemservice.domain.exception.SystemServiceException;
import com.bwda.dsrs.systemservice.domain.form.group.GroupCreateForm;
import com.bwda.dsrs.systemservice.domain.form.group.GroupQueryForm;
import com.bwda.dsrs.systemservice.domain.form.group.GroupUpdateForm;
import com.bwda.dsrs.systemservice.domain.form.user.UserForm;
import com.bwda.dsrs.systemservice.domain.po.group.GroupPo;
import com.bwda.dsrs.systemservice.domain.po.user.UserPo;
import com.bwda.dsrs.systemservice.domain.po.usergroup.UserGroupPo;
import com.bwda.dsrs.systemservice.domain.vo.group.GroupVo;
import com.bwda.dsrs.systemservice.service.GroupService;
import com.bwda.dsrs.systemservice.service.OrgService;
import com.bwda.dsrs.systemservice.service.UserGroupService;
import com.bwda.dsrs.systemservice.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 自定义用户组
 *
 * @author liangjianyong
 * @date 2019/4/13
 */
@RestController
@RequestMapping("/s/group")
@Api(value = "/s/group", tags = "用户组,用户组名称不重复")
public class GroupController extends BaseController {

    @Autowired
    private GroupService groupService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserGroupService userGroupService;

    @Autowired
    private OrgService orgService;

    @ApiOperation(value = "查询用户组,用户组名称不重复", notes = "查询用户组,用户组名称不重复", httpMethod = "GET")
    @Loggable(descp = "查询用户组,用户组名称不重复", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/query", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<GroupVo> query(@ApiParam(value = "组ID", required = true) @RequestParam(value = "id") Long id) throws SystemServiceException {
        GroupPo po = groupService.queryWithValid(id);
        GroupVo vo = CopyUtil.transfer(po, GroupVo.class);
        return getSuccessResult(vo);
    }

    @ApiOperation(value = "查询用户组,用户组名称不重复", notes = "查询用户组,用户组名称不重复", httpMethod = "GET")
    @Loggable(descp = "查询用户组详细信息", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryDetail", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<UserPo>> queryDetail(@ModelAttribute @Valid GroupQueryForm form) throws SystemServiceException {
        UserCondition condition = new UserCondition();
        //装载
        condition.setGroupId(form.getId());
        condition.setPageSize(form.getPageSize());
        condition.setPageNum(form.getPageNum());
        UserGroupCondition ugcondition = new UserGroupCondition();
        ugcondition.setGroupId(form.getId());
        List<UserPo> poList = new ArrayList<>();
        //查询该用户组的人员数量
        int count = userGroupService.queryCount(ugcondition);
        if (count > 0) {
            //查询该用户组的人员
            poList = userService.queryUserByGroupId(condition);
        }
        return getSuccessResult(getPageResponse(form, count, poList));
    }

    @ApiOperation(value = "查询用户组,用户组名称不重复数量", notes = "查询用户组,用户组名称不重复数量", httpMethod = "GET")
    @Loggable(descp = "查询用户组数量", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryCount", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<Integer> queryCount(@RequestBody @Valid GroupQueryForm form) throws SystemServiceException {
        GroupCondition condition = this.getConditionByQueryForm(form);
        int count = groupService.queryCount(condition);
        return getSuccessResult(count);
    }

    @ApiOperation(value = "根据组织查询用户表列表(带分页)", notes = "根据组织查询用户表列表(带分页)", httpMethod = "POST")
    @Loggable(descp = "根据组织查询用户表列表(带分页)", type = LogTypeEnum.QUERY, include = "")
    @PostMapping(value = "/queryPageListByOrg")
    public ResponseEntity<CentreCutPageResponse<UserPo>> queryUserGroupList(@ModelAttribute @Valid GroupQueryForm form) throws SystemServiceException {
        UserCondition condition = CopyUtil.transfer(form, UserCondition.class);
        List<UserPo> poList = new ArrayList<>();
        int count = userService.queryCount(condition);
        if (count > 0) {
            poList = userService.queryList(condition);
        }
        if (form.getId() != null) {
            UserGroupCondition gcondition = new UserGroupCondition();
            gcondition.setGroupId(form.getId());
            List<UserGroupPo> listPo = userGroupService.queryList(gcondition);
            if (listPo != null && listPo.size() > 0) {
                for (UserGroupPo userGroupPo : listPo) {
                    for (UserPo userPo : poList) {
                        if (StringUtils.equals(userGroupPo.getUserCode(), userPo.getUserCode())) {
                            userPo.setCheckedFlag(true);
                            continue;
                        }

                    }
                }
            }
        }

        return getSuccessResult(getPageResponse(form, count, poList));
    }


    @ApiOperation(value = "查询用户组,用户组名称不重复列表", notes = "查询用户组,用户组名称不重复列表", httpMethod = "GET")
    @Loggable(descp = "查询用户组,用户组名称不重复列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<GroupVo>> queryList(@ModelAttribute @Valid GroupQueryForm form) throws SystemServiceException {
        GroupCondition condition = this.getConditionByQueryForm(form);
        condition.setStatus(Constants.StateType.ENABLE);
        List<GroupPo> poList = groupService.queryList(condition);
        List<GroupVo> voList = CopyUtil.transfer(poList, GroupVo.class);
        appendUserNames(voList);

        return getSuccessResult(getListResponse(voList));
    }

    private void appendUserNames(List<GroupVo> voList) {

        for (GroupVo groupVo : voList) {
            String adminCodes = groupVo.getAdminUserCode();

            List<UserForm> userForms = userService.queryUserByCode(adminCodes);
            StringBuilder names = new StringBuilder();
            for (UserForm userForm : userForms) {
                names.append(userForm.getUserName());
            }
            groupVo.setAdminUserName(names.toString());
        }


    }

    @ApiOperation(value = "查询用户组,用户组名称不重复列表", notes = "查询用户组,用户组名称不重复列表", httpMethod = "GET")
    @Loggable(descp = "查询用户组,用户组名称不重复列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryListRequestBody", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<GroupVo>> queryListRequestBody(@RequestBody @Valid GroupQueryForm form) throws SystemServiceException {
        return queryList(form);
    }

    @ApiOperation(value = "查询用户组,用户组名称不重复列表", notes = "查询用户组,用户组名称不重复列表", httpMethod = "GET")
    @RequestMapping(value = "/queryEnableList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<GroupVo>> queryEnableList(@ModelAttribute @Valid GroupQueryForm form) throws SystemServiceException {
        GroupCondition condition = this.getConditionByQueryForm(form);
        condition.setStatus(Constants.StateType.ENABLE);
        List<GroupPo> poList = groupService.queryList(condition);
        List<GroupVo> voList = CopyUtil.transfer(poList, GroupVo.class);
        return getSuccessResult(getListResponse(voList));
    }

    @ApiOperation(value = "查询用户组,用户组名称不重复列表(带分页)", notes = "查询用户组,用户组名称不重复列表(带分页)", httpMethod = "GET")
    @Loggable(descp = "查询用户组列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryPage", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<GroupVo>> queryPage(@RequestBody @Valid GroupQueryForm form) throws SystemServiceException {
        return queryLocalPageList(form);
    }

    @ApiOperation(value = "查询用户组,用户组名称不重复列表(带分页)", notes = "查询用户组,用户组名称不重复列表(带分页)", httpMethod = "GET")
    @Loggable(descp = "查询用户组(带分页)", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryPageList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<GroupVo>> queryPageList(@ModelAttribute @Valid GroupQueryForm form) throws SystemServiceException {
        return queryLocalPageList(form);
    }

    @ApiOperation(value = "查询用户组,用户组名称不重复列表(带分页)(跨服务使用)", notes = "查询用户组,用户组名称不重复列表(带分页(跨服务使用))", httpMethod = "GET")
    @Loggable(descp = "查询用户组(带分页)(跨服务使用)", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryGroupPageList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<GroupVo>> queryGroupPageList(@RequestBody @Valid GroupQueryForm form) throws SystemServiceException {
        return queryLocalPageList(form);
    }

    @ApiOperation(value = "根据userCode查询组织信息", notes = "查询用户组,用户组名称不重复列表(带分页)", httpMethod = "GET")
    @Loggable(descp = "根据userCode查询组织信息", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryGroupListByUserCode", method = {RequestMethod.GET, RequestMethod.POST})
    public List<GroupVo> queryGroupListByUserCode(@ApiParam(value = "用户code", required = true) @RequestParam(value = "userCode") String userCode) throws SystemServiceException {
        List<GroupPo> groupPoList = groupService.queryGroupListByUserCode(userCode);
        List<GroupVo> voList = CopyUtil.transfer(groupPoList, GroupVo.class);
        return voList;
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "新增用户组,用户组名称不重复", notes = "新增用户组,用户组名称不重复", httpMethod = "POST")
    @Loggable(descp = "新增用户组", type = LogTypeEnum.CREATE, include = "")
    @RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<GroupVo> add(@ModelAttribute @Valid GroupCreateForm form, HttpServletRequest request) throws SystemServiceException {
        GroupPo po = CopyUtil.transfer(form, GroupPo.class);
        String userCode = getUserCode();
        if (StringUtils.isBlank(userCode)) {
            logger.error("获取用户信息异常");
            return getSuccessResult("获取不到用户");
        }
        if (po.getAdminUserCode() == null || "".equals(po.getAdminUserCode())) {
            po.setAdminUserCode(Constants.GROUP_ADMIN_CODE);
        }
        po.setCreateUserCode(userCode);
        //添加自定义组记录
        groupService.insert(po);
        //添加用户-自定义组关联关系
        userGroupService.updateUserGroup(po.getId(), form.getUserCodeList());
        GroupVo vo = CopyUtil.transfer(po, GroupVo.class);
        return getSuccessResult(vo);
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "修改用户组,用户组名称不重复", notes = "修改用户组,用户组名称不重复", httpMethod = "POST")
    @Loggable(descp = "修改用户组", type = LogTypeEnum.UPDATE, include = "")
    @RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity update(@ModelAttribute @Valid GroupUpdateForm form, HttpServletRequest request) throws SystemServiceException {
        GroupPo po = CopyUtil.transfer(form, GroupPo.class);
        String userCode = getUserCode();
        if (StringUtils.isBlank(userCode)) {
            logger.error("获取用户信息异常");
            return getSuccessResult("获取不到用户");
        }
        po.setUpdateUserCode(userCode);
        po.setUpdateTime(new Date());
        //更新自定义组信息
        groupService.update(po);
        //更新用户-自定义组关联关系
        userGroupService.updateUserGroup(form.getId(), form.getUserCodeList());
        return getSuccessResult();
    }

    /**
     * 删除/批量删除
     *
     * @param id
     * @return
     * @throws SystemServiceException
     */
    @NeedRole("sysadminrole")
    @ApiOperation(value = "删除用户组,用户组名称不重复", notes = "删除用户组,用户组名称不重复", httpMethod = "POST")
    @Loggable(descp = "删除用户组", type = LogTypeEnum.DELETE, include = "")
    @RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity delete(@ModelAttribute @Valid @RequestParam(value = "id") List<Integer> id) throws SystemServiceException {
        if (id == null || id.size() == 0) {
            return getFailResult("参数不能为空");
        } else if (id.size() > 1) {
            //批量删除
            for (Integer groupId : id) {
                groupService.delete(groupId);
                userGroupService.updateUserGroup(groupId, null);
            }
        } else {
            groupService.delete(id.get(0));
            userGroupService.updateUserGroup(id.get(0), null);
        }
        return getSuccessResult();
    }

    private ResponseEntity<CentreCutPageResponse<GroupVo>> queryLocalPageList(GroupQueryForm form) {
        GroupCondition condition = this.getConditionByQueryForm(form);
        List<GroupVo> voList = new ArrayList<>();
        int count = groupService.queryCount(condition);
        if (count > 0) {
            List<GroupPo> poList = groupService.queryList(condition);
            for (GroupPo groupPo : poList) {
                UserGroupCondition gcondition = new UserGroupCondition();
                gcondition.setGroupId(groupPo.getId());
                List<UserGroupPo> listPo = userGroupService.queryList(gcondition);
                if (listPo != null && listPo.size() > 0) {
                    StringBuffer userCodesBuffer = new StringBuffer();
                    for (UserGroupPo userGroupPo : listPo) {
                        userCodesBuffer.append(userGroupPo.getUserCode()).append(",");
                    }
                    groupPo.setUserCodes(userCodesBuffer.substring(0, userCodesBuffer.length() - 1));
                }
                if (Constants.ZERO_STR.equals(groupPo.getUserCodes())) {
                    groupPo.setUserCodes("");
                }

                //查询管理员姓名
                String adminCodes = groupPo.getAdminUserCode();
                if (StringUtils.isNotEmpty(adminCodes)) {
                    String[] users = adminCodes.split(",");
                    List<UserForm> userForms = userService.queryUserByUserCodeList(users);
                    StringBuilder names = new StringBuilder();
                    for (UserForm userForm : userForms) {
                        names = names.append(userForm.getUserName() + " ");
                    }

                    groupPo.setAdminUserName(names.toString());
                }
            }
            voList = CopyUtil.transfer(poList, GroupVo.class);
        }
        return getSuccessResult(getPageResponse(form, count, voList));
    }

    /**
     * GroupQueryForm转换为GroupCondition
     *
     * @param form
     * @return
     */
    private GroupCondition getConditionByQueryForm(GroupQueryForm form) {
        GroupCondition condition = CopyUtil.transfer(form, GroupCondition.class);
        return condition;
    }

}
